import { useState, useRef } from 'react';
import { View, Input, Text } from '@tarojs/components';
import { AtButton } from 'taro-ui';
import IconFont from '@/assets/Iconfont';
import cssModule from './index.module.scss';
import { sendSms, smsLogin, syncLocation } from '@/business/services/user/login/login';
import { cityTreeListStore } from '@/business/store/city/city';
import { getAuthCode, setAuthCode } from '@/base/auth/authCode';
import { wxLogin } from '@/business/services/user/login/login';
import Taro from '@tarojs/taro';
import { initUser } from '@/business/services/im';

/**
 * @description 手机验证码登录
 * @author Shawn
 */

interface IPhoneLoginProps {
  agreementChecked: string[]
}

export default function PhoneLogin(props: IPhoneLoginProps) {
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [countdown, setCountdown] = useState(0);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // 设置当前城市
  const setLocation = async () => {
    const res = await Taro.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
    });
    const { latitude, longitude } = res;

    if (latitude && longitude) {
      await syncLocation({ latitude, longitude })
    }
  }

  // 微信授权登录
  const setUserAuthCode = async () => {
    if (!props.agreementChecked.length) {
      Taro.showToast({
        title: '请同意用户协议和隐私政策',
        icon: 'none'
      })
      return
    }
    await setAuthCode()
    const authCode = await getAuthCode()
    const res = await wxLogin({
      code: authCode
    })
    Taro.setStorageSync('openid', res.data.openid);
    Taro.setStorageSync('openToken', res.data.token);
    Taro.setStorageSync('userId', res.data.userId);
    const userSig = Taro.getStorageSync('imUserSig');
    await setLocation()
    if (!userSig) {
      const imRes = await initUser({})
      Taro.setStorageSync('imUserSig', imRes.data.imUserId);
    }
    Taro.setStorageSync('isLogin', true);
    // 没注册过
    if (!res.data.registered) {
      Taro.redirectTo({
        url: `/pages/register/index?openid=${res.data.openid}`,
      });
    } else if (res.data.firstLogin) {
      Taro.redirectTo({
        url: `/subPackages/person/index`,
      });
    } else {
      Taro.reLaunch({
        url: `/pages/index/index`,
      });
    }
  }

  // 获取城市数据
  const getCityTreeList = async () => {
    await cityTreeListStore.getState().getCityTreeList();
  }

  // 发送验证码
  const handleSendCode = () => {
    if (countdown > 0) return;
    // 这里可以添加手机号校验逻辑
    setCountdown(60);
    timerRef.current = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timerRef.current!);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    // TODO: 这里可以添加发送验证码的接口调用
    sendSms({ scene: 'login', phone: phone });
  };

  const onSmsLogin = async () => {
    if (!props.agreementChecked.length) {
      Taro.showToast({
        title: '请同意用户协议和隐私政策',
        icon: 'none'
      })
      return
    }
    if (!phone.trim() || !code.trim()) {
      Taro.showToast({ title: '请填写手机号和验证码', icon: 'none' })
      return
    }
    if (props.agreementChecked.length === 0) {
      Taro.showToast({
        title: '请同意用户协议和隐私政策',
        icon: 'none'
      })
      return
    }

    const res = await smsLogin({
      cellphone: phone,
      smsCode: code,
    })
    if (!res.success) {
      return
    }
    Taro.setStorageSync('openToken', res.data);

    await setAuthCode();
    const authCode = await getAuthCode();
    const authRes = await wxLogin({
      code: authCode,
    });
    Taro.setStorageSync('userId', authRes.data.userId);
    Taro.setStorageSync('openid', authRes.data.openid);
    const userSig = Taro.getStorageSync('imUserSig');
    await setLocation()
    if (!userSig) {
      const imRes = await initUser({})
      Taro.setStorageSync('imUserSig', imRes.data.imUserId);
    }
    Taro.setStorageSync('isLogin', true);
    getCityTreeList()

    Taro.reLaunch({
      url: `/pages/index/index`,
    });
  }

  const [phoneCursor, setPhoneCursor] = useState(0)
  const [codeCursor, setCodeCursor] = useState(0)

  return (
    <View className={cssModule.container}>
      <View className={cssModule.phoneRow}>
        <IconFont name='shouji' size={36} />
        <Input
          className={cssModule.input}
          placeholder='手机号'
          cursor={phoneCursor}
          type='number'
          value={phone}
          onInput={(e) => {
            setPhone(e.detail.value),
              setPhoneCursor(e.detail.cursor)
          }}
          maxlength={11}
        />
      </View>
      <View className={cssModule.codeRow}>
        <IconFont name='mima' size={36} />
        <Input
          className={cssModule.input}
          placeholder='验证码'
          type='number'
          value={code}
          cursor={codeCursor}
          onInput={(e) => {
            setCode(e.detail.value)
            setCodeCursor(e.detail.cursor)
          }}
          maxlength={6}
        />
        <View className={cssModule.sendBtn} onClick={handleSendCode}>
          {countdown > 0 ? `${countdown}s后重试` : '发送验证码'}
        </View>
      </View>
      <View className={cssModule.loginBtn} onClick={onSmsLogin}>
        <AtButton type='primary'>登录</AtButton>
      </View>
      <View className={cssModule.wechatLogin}>
        <AtButton type='secondary' onClick={setUserAuthCode}>
          <View className={cssModule.wechatLoginContent}>
            <IconFont name='wechat' size={36} color='#6190e8' />
            <Text className='ml-2'>微信授权快捷登录</Text>
          </View>
        </AtButton>
      </View>
    </View>
  );
}
